//
//  HOTRegisterViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-8-29.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTRegisterViewController.h"
#import "ZZZDatePicker.h"
#import "HOTCommLabel.h"
#import "HOTCommTextField.h"
#import "ZZZUIScrollView+Extends.h"
#import "ZZZPullDownView.h"
#import "HOTMenuViewController.h"
#import "ZZZNSString+Extend.h"
#import "UITextField+extend.h"
#import "ZZZPopupView.h"
#import "HOTCommPullDonwView.h"

@interface HOTRegisterViewController () <UITextFieldDelegate,ZZZPopupViewDelegate> {
    
    HOTCommTextField *_nickNameText;
    HOTCommTextField *_emailText;
    HOTCommTextField *_passwordText;
    //HOTCommTextField *_sexText;
    HOTCommTextField *_birthdayText;
    //HOTCommTextField *_addressText;
    ZZZDatePicker *_datePicker;
    
    ZZZPullDownView *_sexPullDownView;
    ZZZPullDownView *_cityPullDownView;
    HOTCommTextField *_addressText;
    
}
@end

@implementation HOTRegisterViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNaviTitle:@"新規登録" fontSize:24 fontName:HOTTitleFont_ROUNDED_X];
    
    //[_mainScrollView setDelaysContentTouches:YES];
    //[_mainScrollView setScrollEnabled:NO];
    
    [self createRightBtnWithType:HOTNaviBarRightBtnDone];
    
    [self initView];
}


#pragma mark - textField delegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    
    [_mainScrollView scrollViewToVisible:textField animated:YES];
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    
    return YES;
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    
    [textField resignFirstResponder];
    
    return YES;
}


#pragma mark - ZZZPopupViewDelegate
-(void)popupView:(ZZZPopupView *)popupView buttonKind:(ZZZPopupViewBtnKind)btnKind {
    [super popupView:popupView buttonKind:btnKind];
    
    if (popupView.tag == 101) {
        
        HOTMenuViewController *menuVC = [[HOTMenuViewController alloc] initWithNibName:@"HOTMenuViewController" bundle:nil];
        
        [self.navigationController pushViewController:menuVC animated:YES];
    }
    
}

#pragma mark - 按钮事件
-(void)rightBtnClicked:(HOTCommBtn *)sender {
    
    [self hiddenKeyBoard];
    //    HOTMenuViewController *menuVC = [[HOTMenuViewController alloc] initWithNibName:@"HOTMenuViewController" bundle:nil];
    //
    //    [self.navigationController pushViewController:menuVC animated:YES];
    
    if([self checkParametersValid]) {
        
        [self registerUser];
    }
}

#pragma  mark - 私有方法
-(void)registerUser {
    
    [self showLoadingWithMessage:MSG_REGISTER];
    //審査のため、生年月日、性別、住所を新規登録項目から外す　Start 2014/12/17
    //    NSDictionary *parameters = @{REQ_KEY_USER_NICK:_nickNameText.text,
    //                                 REQ_KEY_USER_EMAIL:_emailText.text,
    //                                 REQ_KEY_USER_PWD:_passwordText.text,
    //                                 REQ_KEY_USER_SEX:_sexPullDownView.selectedModel.value,
    //                                 REQ_KEY_USER_BIRTH:_birthdayText.text,
    //                                 REQ_KEY_USER_CITY_ID:_cityPullDownView.selectedModel.value,
    //                                 REQ_KEY_DISTRICT:_addressText.text};
    NSDictionary *parameters = @{REQ_KEY_USER_NICK:_nickNameText.text,
                                 REQ_KEY_USER_EMAIL:_emailText.text,
                                 REQ_KEY_USER_PWD:_passwordText.text,
                                 REQ_KEY_USER_SEX:@"",
                                 REQ_KEY_USER_BIRTH:@"",
                                 REQ_KEY_USER_CITY_ID:@"",
                                 REQ_KEY_DISTRICT:@""};
    //審査のため、生年月日、性別、住所を新規登録項目から外す　End 2014/12/17
    __unsafe_unretained HOTRegisterViewController *tempObj = self;
    [self requestWithURL:HOT_URL_REGISTER Parameters:parameters success:^(NSInteger result, NSDictionary * data) {
        
        
        
                NSLog(@"%@", @"注册成功");
        
        NSString *uid = [data objectForKey:REQ_KEY_USER_ID];
        NSString *token = [data objectForKey:REQ_KEY_USER_TOKEN];
        
        [tempObj.userInfo resgistWithId:uid token:token];
        
        self.userInfo.nick = _nickNameText.text;
        self.userInfo.email = _emailText.text;
        self.userInfo.pwd = _passwordText.text;
        self.userInfo.sex = _sexPullDownView.selectedModel.value;
        self.userInfo.birth = _birthdayText.text;
        self.userInfo.city_id = _cityPullDownView.selectedModel.value;
        self.userInfo.district = _addressText.text;
        
        [self.userInfo save];
        
        [tempObj showSuccessWithMessage:MSG_REGISTER_SUCCESS complection:^{
            
            
            [tempObj.hudManager showIndeterminateWithMessage:MSG_LOGINING duration:1.5 complection:^{
                
                if ([self.delegate respondsToSelector:@selector(registerSuccessed)]) {
                    [self.delegate registerSuccessed];
                }
                
//                HOTMenuViewController *menuVC = [[HOTMenuViewController alloc] initWithNibName:@"HOTMenuViewController" bundle:nil];
//                
//                [tempObj.navigationController pushViewController:menuVC animated:YES];
            }];
        }];
        
        //        ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:@"注册成功" delegate:self cancelButtonTitle:nil otherButtonTitle:ALERT_BTN_OK];
        //
        //        [popupView showInWindow];
        
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:errMsg delegate:nil cancelButtonTitle:nil otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(BOOL)checkParametersValid {
    
    NSString *errName = @"";
    HOTInputItemType inputType = 0;
    if ([_nickNameText textIsNullOrEmpty]) {
        
        errName = @"ニックネーム";
        inputType = HOTInputItemText;
    } else if ([_emailText textIsNullOrEmpty]) {
        
        errName = @"メールアドレス";
        inputType = HOTInputItemText;
    } else if ([_passwordText textIsNullOrEmpty]) {
        
        errName = @"パスワード";
        inputType = HOTInputItemText;
    }
    //    else if (_sexPullDownView.selectedModel == nil) {
    //
    //        errName = @"性別";
    //        inputType = HOTInputItemPullDown;
    //    } else if ([_birthdayText textIsNullOrEmpty]) {
    //
    //        errName = @"生年月日";
    //        inputType = HOTInputItemPullDown;
    //    } else if (_cityPullDownView.selectedModel == nil) {
    //
    //        errName = @"お住まいの地域";
    //        inputType = HOTInputItemPullDown;
    //    } else if ([_addressText textIsNullOrEmpty]) {
    //
    //        errName = @"市区町村";
    //        inputType = HOTInputItemText;
    //    }
    
    if (errName.length > 0) {
        
        NSString * errMsg = [self getErrMsgWith:errName itemType:inputType];
        
        ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:errMsg delegate:nil cancelButtonTitle:nil otherButtonTitle:ALERT_BTN_OK];
        
        [popupView showInWindow];
        
        return NO;
    }
    
    
    
    return YES;
}

-(void)initView {
    
    //float orgx = 0.f;
    float orgy = 0.f;
    float paddingTxtX = 15.f;
    float paddingLabX = 27.f;
    float paddingY = 15.f;
    float paddingY_Y = 5.f;
    float txtWidth = 288;
    float txtHeight = 41;
    
    //ニックネーム
    HOTCommLabel *label = [self createLabelWithPoint:CGPointMake(paddingLabX, paddingY) Text:@"ニックネーム"];
    orgy = ZZZ_calcY(label, paddingY_Y);
    _nickNameText = [self createTextWithFrame:CGRectMake(paddingTxtX, orgy, txtWidth, txtHeight)];
    [_mainScrollView addSubview:label];
    [_mainScrollView addSubview:_nickNameText];
    
    //メールアドレス
    orgy = ZZZ_calcY(_nickNameText, paddingY);
    label = [self createLabelWithPoint:CGPointMake(paddingLabX, orgy) Text:@"メールアドレス"];
    orgy = ZZZ_calcY(label, paddingY_Y);
    _emailText = [self createTextWithFrame:CGRectMake(paddingTxtX, orgy, txtWidth, txtHeight)];
    [_mainScrollView addSubview:label];
    [_mainScrollView addSubview:_emailText];
    
    //パスワード（6〜16文字）
    orgy = ZZZ_calcY(_emailText, paddingY);
    label = [self createLabelWithPoint:CGPointMake(paddingLabX, orgy) Text:@"パスワード（6〜16文字）"];
    orgy = ZZZ_calcY(label, paddingY_Y);
    _passwordText = [self createTextWithFrame:CGRectMake(paddingTxtX, orgy, txtWidth, txtHeight)];
    [_passwordText setSecureTextEntry:YES];
    [_mainScrollView addSubview:label];
    [_mainScrollView addSubview:_passwordText];
    //審査のため、生年月日、性別、住所を新規登録項目から外す　Start 2014/12/17
    //    //性別
    //    orgy = ZZZ_calcY(_passwordText, paddingY);
    //    label = [self createLabelWithPoint:CGPointMake(paddingLabX, orgy) Text:@"性別"];
    //    orgy = ZZZ_calcY(label, paddingY_Y);
    //    _sexPullDownView = [[HOTCommPullDonwView alloc] initWithFrame:CGRectMake(paddingTxtX, orgy, txtWidth, txtHeight)];
    //    _sexPullDownView.parentView = _mainScrollView;
    //    [_sexPullDownView setPullEdgesForBounds:CGRectMake(10, 0, -20, 0)];
    //    //[_sexPullDownView setTitleEdgeInsets:UIEdgeInsetsMake(0, -100, 0, 0)];
    //    [_sexPullDownView setTitleFont:ZZZ_fontWithName(kHOT_FONT_ROUNDED_X, 16)];
    //
    //    __unsafe_unretained HOTRegisterViewController *blockObj = self;
    //    __block UIScrollView *blocScrollView = _mainScrollView;
    //    _sexPullDownView.WhenBtnClicked = ^ (void) {
    //
    //        [blockObj hiddenKeyBoard];
    //        [blocScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    //
    //    };
    //    UIImage *bgImage = [UIImage imageNamed:@"pulldown_open"];
    //    bgImage = [bgImage resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20)];
    //    UIImageView *openBgView = [[UIImageView alloc] initWithImage:bgImage];
    //    //openBgView.frame = CGRectMake(0, 0, 288, 100);
    //    [_sexPullDownView setOpenListBackground:openBgView];
    //
    //
    //    ZZZPullDownModel *model = [[ZZZPullDownModel alloc] init];
    //    model.titleStr = @"男";
    //    model.value = @"1";
    //
    //    ZZZPullDownModel *model2 = [[ZZZPullDownModel alloc] init];
    //    model2.titleStr = @"女";
    //    model2.value = @"2";
    //    [_sexPullDownView setSelectedModel:model];
    //
    //    [_sexPullDownView setPullDownModelList:@[model, model2]];
    //
    //    [_sexPullDownView setBackground:[UIImage imageNamed:@"pulldown_box"]];
    //
    //    [_mainScrollView addSubview:label];
    //    [_mainScrollView addSubview:_sexPullDownView];
    //
    //    //生年月日
    //    orgy = ZZZ_calcY(_sexPullDownView, paddingY);
    //    label = [self createLabelWithPoint:CGPointMake(paddingLabX, orgy) Text:@"生年月日"];
    //    orgy = ZZZ_calcY(label, paddingY_Y);
    //    _birthdayText = [self createTextWithFrame:CGRectMake(paddingTxtX, orgy, txtWidth, txtHeight)];
    //    [_mainScrollView addSubview:label];
    //    [_mainScrollView addSubview:_birthdayText];
    //
    //    __block UITextField *blockBirthdayText = _birthdayText;
    //    _datePicker = [ZZZDatePicker createWithTextField:_birthdayText
    //                                 doneCompletionBlock:^(NSDate *selDate) {
    //
    //                                     NSString *dateStr = [ZZZUtils formartDate:selDate withStyle:@"yyyy-MM-dd"];
    //                                     blockBirthdayText.text = [dateStr toStr];
    //
    //                                 }
    //                               cancelCompletionBlock:^{
    //
    //
    //                               }];
    //    [_datePicker setDatePickerMode:UIDatePickerModeDate];
    //
    //    //お住まいの地域
    //    orgy = ZZZ_calcY(_birthdayText, paddingY);
    //    label = [self createLabelWithPoint:CGPointMake(paddingLabX, orgy) Text:@"お住まいの地域"];
    //    orgy = ZZZ_calcY(label, paddingY_Y);
    //    _cityPullDownView = [[HOTCommPullDonwView alloc] initWithFrame:CGRectMake(paddingTxtX, orgy, txtWidth, txtHeight)];
    //    _cityPullDownView.parentView = _mainScrollView;
    //
    //    _cityPullDownView.WhenBtnClicked = ^(void) {
    //
    //        [blockObj hiddenKeyBoard];
    //        [blocScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    //    };
    //
    //    [_cityPullDownView setPullEdgesForBounds:CGRectMake(10, 0, -20, 0)];
    //    //[_cityPullDownView setTitleEdgeInsets:UIEdgeInsetsMake(0, -100, 0, 0)];
    //    [_cityPullDownView setTitleFont:ZZZ_fontWithName(kHOT_FONT_ROUNDED_X, 16)];
    //
    //    bgImage = [UIImage imageNamed:@"pulldown_open"];
    //    bgImage = [bgImage resizableImageWithCapInsets:UIEdgeInsetsMake(20, 20, 20, 20)];
    //    openBgView = [[UIImageView alloc] initWithImage:bgImage];
    //    //openBgView.frame = CGRectMake(0, 0, 288, 100);
    //    [_cityPullDownView setOpenListBackground:openBgView];
    //
    //    NSArray *modelList = [HOTUtils getPullModelListFromPlist];
    //    [_cityPullDownView setSelectedModel:[modelList firstObject]];
    //    [_cityPullDownView setPullDownModelList:modelList];
    //
    //    [_cityPullDownView setBackground:[UIImage imageNamed:@"pulldown_box"]];
    //    [_mainScrollView addSubview:label];
    //    [_mainScrollView addSubview:_cityPullDownView];
    //
    //    //市区町村
    //    orgy = ZZZ_calcY(_cityPullDownView, paddingY);
    //    label = [self createLabelWithPoint:CGPointMake(paddingLabX, orgy) Text:@"市区町村"];
    //    orgy = ZZZ_calcY(label, paddingY_Y);
    //    _addressText = [self createTextWithFrame:CGRectMake(paddingTxtX, orgy, txtWidth, txtHeight)];
    //    [_mainScrollView addSubview:label];
    //    [_mainScrollView addSubview:_addressText];
    //
    //    orgy = ZZZ_calcY(_addressText, 20);
    
    orgy = ZZZ_calcY(_passwordText, paddingY);
    //審査のため、生年月日、性別、住所を新規登録項目から外す　End　2014/12/17
    NSString *attentionStr = @"※注意\niPhoneからその他スマホに機種変更すると「＠i.softbank.jp」＠メールアドレスが利用できない場合があります。その際、パスワード再発行時に運営からのメールが届かなくなり再度会員登録していただくことになりますので登録するメールアドレスにご注意ください。\nまた、登録メールアドレスは途中変更できません。";
    
    UILabel *attentionLabel = [[UILabel alloc] initWithFrame:CGRectMake(paddingLabX, orgy, 320-paddingLabX *2, 0 )];
    
    attentionLabel.numberOfLines = 0;
    attentionLabel.textColor = [UIColor whiteColor];
    attentionLabel.text = attentionStr;
    attentionLabel.font = ZZZ_fontWithName(kHOT_FONT_HIRAGINO_KAKU_W6, 12);
    NSMutableAttributedString *attributedString1 = [[NSMutableAttributedString alloc] initWithString:attentionStr];
    NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:5];
    [attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [attentionStr length])];
    [attentionLabel setAttributedText:attributedString1];
    [attentionLabel sizeToFit];
    
    [_mainScrollView addSubview:attentionLabel];
    
    [_mainScrollView setContentSize:CGSizeMake(320, ZZZ_calcY(attentionLabel, 20))];
}

-(HOTCommTextField *)createTextWithFrame:(CGRect)frame{
    
    HOTCommTextField *field = [[HOTCommTextField alloc] initWithFrame:frame];
    field.delegate = self;
    field.background = [UIImage imageNamed:@"text_box"];
    [field setTextRectForBounds:CGRectMake(20, 2, frame.size.width-30, 100)];
    field.returnKeyType = UIReturnKeyDone;
    field.font = [UIFont fontWithName:kHOT_FONT_HIRAGINO_KAKU_W6 size:16];
    field.textColor = [UIColor blackColor];
    
    return field;
}

-(HOTCommLabel *)createLabelWithPoint:(CGPoint)point Text:(NSString *)text{
    
    CGRect labelFrame = [text boundingRectWithSize:CGSizeMake(320-30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:ZZZ_fontWithName(kHOT_FONT_ROUNDED_X, 18)} context:nil];
    
    HOTCommLabel *label = [HOTCommLabel createLabelFrame:CGRectMake(point.x, point.y, labelFrame.size.width,
                                                                    labelFrame.size.height)
                                                    font:ZZZ_fontWithName(kHOT_FONT_ROUNDED_X, 18)];
    label.text = text;
    label.textColor = [UIColor whiteColor];
    
    return label;
}


-(void)hiddenKeyBoard {
    
    [_passwordText resignFirstResponder];
    [_nickNameText resignFirstResponder];
    [_emailText resignFirstResponder];
    [_birthdayText resignFirstResponder];
    [_addressText resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
